package org.example.erp.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.erp.domain.Units;
import org.example.erp.service.UnitsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;




@RestController
@RequestMapping("/api")
public class UnitsController {
    @Autowired
   private UnitsService unitsService;

    @GetMapping("/unit/find")
    public DataResult getColorList(@RequestParam(required = false) String unitCode,
                                   @RequestParam(required = false) String unitName,
                                   @RequestParam(value = "currentPage", defaultValue = "1") int currentPage,
                                   @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        // 检查是否需要查询全部数据
        boolean fetchAll = currentPage < 0;

        Page<Units> page = new Page<Units>(currentPage, pageSize);
        QueryWrapper<Units> queryWrapper = new QueryWrapper();
        if (unitCode != null && !"".equals(unitCode)) {
            queryWrapper.lambda().like(Units::getUnit, unitCode);
        }
        if (unitName != null && !"".equals(unitName)) {
            queryWrapper.lambda().like(Units::getUnitName, unitName);
        }
        if (fetchAll) {
            List<Units> list = unitsService.list(queryWrapper);
            return DataResult.success(list);
        } else {
            page = unitsService.page(page, queryWrapper);
            return DataResult.success(page);
        }
    }

    @PostMapping("/unit/insert")
    public DataResult addFind(@RequestBody Units form) {
        boolean save = unitsService.save(form);
        return DataResult.success(save ? "成功" : "失败");
    }

    @PutMapping("/unit/update")
    public DataResult updateFind(@RequestBody Units form) {
        boolean update = unitsService.updateById(form);
        return DataResult.success(update ? "成功" : "失败");
    }

    @DeleteMapping("/unit/delete")
    public DataResult deleteFind(@RequestBody List<String> id) {
        boolean delete = unitsService.removeByIds(id);
        return DataResult.success(delete ? "成功" : "失败");
    }
}
